define(["angularAMD", "moment"], function (angularAMD, moment) {
    angularAMD.service('B0234Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog','$calculater', "$gallery",
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog,$calculater, $gallery) {
            /**
             * options = {
             *     plotItem: {},
             *     feedback: function
             * }
            **/
            this.init = function (options) {

                function already_bind_mold_no(callback){
                    // var data = {
                    //     moldList:[
                    //         {
                    //             mold_no: 'A005',
                    //             cavity_standard_qty: 4,
                    //             current_cavity_health_qty: 4,
                    //             cavity_health_qty: 3,
                    //         },
                    //         {
                    //             mold_no: 'A006',
                    //             cavity_standard_qty: 4,
                    //             current_cavity_health_qty: 4,
                    //             cavity_health_qty: 2,
                    //         }
                    //     ]
                    // };
                    // if(callback)
                    //     callback(data);

                    var content = {
                        mo_no: options.plotItem.wo_no
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_INJECT.injection_mould_info_get',
                        content: content,
                        success: function (data) {
                            if (callback)
                                callback(data);
                        }
                    });
                };

                // 掃描取得模治具資料
                function mold_no_info_get(mold_no, callback){
                    // if(mold_no == 'A004'){
                    //     var itemList = {
                    //         mold_no: 'A004',
                    //         mold_type: 'A004',
                    //         mold_class: 'A004',
                    //         cavity_standard_qty: 6,
                    //         cavity_health_qty: 5,
                    //     };  
                    //     if(callback)
                    //         callback(itemList);
                    // } else {
                    //     if(callback)
                    //         callback({});
                    // };

                    $MMWService.pageNumberInfoGet({
                        page_mode : 'injection_mould_info_get',
                        query_condition_info:[
                            {column_name:'a.AccessoryNo', query_mode:'0', value: mold_no, merge_condition_model:'AND'},
                        ]
                    }, function(itemList){
                        if(callback)
                            callback(itemList[0]);
                    });
                };

                // 取得穴數調整原因資料
                function cavity_reason_list_info_get(callback){
                    // var itemList = [
                    //     {cavity_reason_no: '1', cavity_reason_name: $filter('translate')('毛邊塞穴1')},
                    //     {cavity_reason_no: '2', cavity_reason_name: $filter('translate')('毛边塞穴2')},
                    //     {cavity_reason_no: '3', cavity_reason_name: $filter('translate')('毛边塞穴3')},
                    //     {cavity_reason_no: '4', cavity_reason_name: $filter('translate')('毛边塞穴4')},
                    //     {cavity_reason_no: '5', cavity_reason_name: $filter('translate')('毛边塞穴5')}
                    // ];
                    // if(callback)
                    //     callback(itemList);

                    $MMWService.pageNumberInfoGet({
                        page_mode : 'injection_mould_reason_info_get',
                        query_condition_info:[
                            {column_name:'ReasonType', query_mode:'0', value: '4', merge_condition_model:'AND'}
                        ]
                    }, function(itemList){
                        if(callback)
                            callback(itemList);
                    });
                };

                // 送回資料
                function mold_list_process(content, callback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_INJECT.injection_mould_set_process',
                        content: content,
                        success: function (data) {
                            if (callback)
                                callback(data);
                        }
                    });
                };

                var openDialog = function(data){
                    $mdDialog.dialog(
                        'module/moduleB/program/B02/B0234/B0234.html',
                        function (dialog) {
                            return {
                                css_url: 'module/moduleB/program/B02/B0234/B0234.css',
                                wo_no: options.plotItem.wo_no,
                                product_no: options.plotItem.item_no,
                                product_name: options.plotItem.item_name,
                                mold_no: '',
                                moldList: data.moldList,
                                back: function(){
                                    dialog.hide();
                                },
                                // 掃描查詢
                                input_mold_no_callback: function(mold_no){
                                    mold_no_info_get(mold_no, function(itemList){
                                        if(typeof(itemList) === 'object' && Object.keys(itemList).length > 0){
                                            // 避免重複輸入
                                            var isInput = true;
                                            for(var i = 0; i < dialog.moldList.length; i++){
                                                if(dialog.moldList[i].mold_no == itemList.mold_no){
                                                    isInput = false;
                                                    break;
                                                }
                                            };
                                            if(isInput){
                                                dialog.mold_no = '';
                                                dialog.moldList.push({
                                                    mold_no: itemList.mold_no,
                                                    cavity_standard_qty: itemList.cavity_standard_qty,
                                                    current_cavity_health_qty: itemList.cavity_health_qty,
                                                    cavity_health_qty: '',
                                                    cavity_reason_no:'',
                                                    cavity_reason_name: ''
                                                });   
                                            } else {
                                                $rootScope.showAlert($filter('translate')('B0234.msg.colunm01'));
                                            };
                                        } else {
                                            $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                                        };
                                    });
                                },
                                barcode_mold_no: function(event){
                                    if(event.keyCode == 13){
                                        dialog.input_mold_no_callback(dialog.mold_no);
                                    }
                                },
                                qrcode_mold_no: function(){
                                    $rootScope.OpenScanner({
                                        after : function(result){
                                            dialog.mold_no = result.text;
                                            dialog.input_mold_no_callback(result.text);
                                        },
                                        exception: function(){
                                            //目前裝置無法使用相機
                                            $rootScope.showAlert($filter('translate')('common.msg.cant_use_camera'));
                                        },
                                        orientation : 'landscape'
                                    });
                                },
                                inputCavityHealthQty: function(event, item){
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function(num,dialog){ 
                                        angular.element(target).removeClass('is-focus');
                                        if(num > item.cavity_standard_qty){
                                            // 健康穴數調整的數量，不能超過標準穴數的數量
                                            $rootScope.showAlert($filter('translate')('B0234.msg.column02', {cavity_standard_qty: item.cavity_standard_qty}));
                                        } else {
                                            item.cavity_health_qty = num;
                                            dialog.hide();
                                        };
                                    },
                                    function(dialog){
                                        angular.element(target).removeClass('is-focus');
                                        dialog.hide();
                                    },
                                    {
                                        defaultNum : item.cavity_health_qty,
                                        decimal : true
                                    });
                                },
                                loadCavityReasonNo: function(item){
                                    // 有修改健康穴數數量，才能選取穴數調整原因！
                                    // 而且有輸入健康穴數數量，一定要選取穴數調整原因！
                                    if(item.cavity_health_qty == ''){
                                        $rootScope.showAlert($filter('translate')('B0234.msg.column03'));
                                    } else {
                                        cavity_reason_list_info_get(function(itemList){
                                            $rootScope.showSelect({
                                                title : $filter('translate')('common.msg.plz_select'),
                                                label : 'cavity_reason_name',
                                                code : 'cavity_reason_no',
                                                list : itemList,
                                                selectCode: item.cavity_reason_name || '',
                                                confirm : function(selectItem, dialog){
                                                    item.cavity_reason_no = selectItem.cavity_reason_no;
                                                    item.cavity_reason_name = selectItem.cavity_reason_name;
                                                    dialog.hide();
                                                }
                                            });
                                        });
                                    };
                                },
                                removeRow: function(index){
                                    dialog.moldList.splice(index, 1);
                                },
                                loadMoldList: function(){
                                    $MMWService.showQueryListPNIG({
                                        page_mode: 'injection_mould_info_get',
                                        pageRecord: 25,
                                        condition: [
                                            {name:$filter('translate')('B0234.queryList.column01'), column_name:'a.AccessoryNo', query_mode:'2', value: ''},
                                        ],
                                        selectCode: '',
                                        header: [
                                            {label:$filter('translate')('B0234.queryList.column01'), code:'mold_no'},
                                            {label:$filter('translate')('B0234.queryList.column02'), code:'mold_type'},
                                            {label:$filter('translate')('B0234.queryList.column03'), code:'mold_class'},
                                            {label:$filter('translate')('B0234.queryList.column04'), code:'cavity_standard_qty'},
                                            {label:$filter('translate')('B0234.queryList.column05'), code:'cavity_health_qty'}
                                        ],
                                        confirm : function(selectItem, dialogType){
                                            for(var i = 0; i < dialog.moldList.length; i++){
                                                if(dialog.moldList[i].mold_no == selectItem.mold_no){
                                                    $rootScope.showAlert($filter('translate')('B0234.msg.column06'));
                                                    return;
                                                } 
                                            };
                                            dialog.moldList.push({
                                                mold_no: selectItem.mold_no,
                                                cavity_standard_qty: selectItem.cavity_standard_qty,
                                                current_cavity_health_qty: selectItem.cavity_health_qty,
                                                cavity_health_qty: '',
                                                cavity_reason_no:'',
                                                cavity_reason_name: ''
                                            });
                                            dialogType.hide();
                                        }
                                    });
                                },
                                confirm: function(){
                                    if(dialog.moldList && dialog.moldList.length > 0){
                                        var content = {
                                            wo_no: dialog.wo_no,
                                            product_no: dialog.product_no,
                                            product_name: dialog.product_name,
                                            mould_data: dialog.moldList
                                        };
                                        var isConfirm = true;
                                        if(content.mould_data && content.mould_data.length > 0){
                                            for(var i = 0; i < content.mould_data.length; i++){
                                                // 如果有調整健康穴數數量，但沒有選擇穴數調整原因時，不能送回資料！
                                                if(content.mould_data[i].cavity_health_qty != '' && content.mould_data[i].cavity_reason_name == ''){
                                                    $rootScope.showAlert($filter('translate')('B0234.msg.column04',{mold_no: content.mould_data[i].mold_no}));
                                                    isConfirm = false;
                                                    break;
                                                } 
                                            };
                                        }
                                        if(isConfirm){
                                            mold_list_process(content,function(){
                                                dialog.hide();
                                                $rootScope.showToast($filter('translate')('common.msg.success'));
                                                if(options.feedback)
                                                    options.feedback();
                                            }); 
                                        }
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0234.msg.column05'));
                                    };  
                                }
                            };
                        }
                    );
                };

                already_bind_mold_no(function(data){
                    for(var i = 0; i < data.moldList.length; i++){
                        // 後台只帶模治具編號、標準穴數、目前健康穴數的資料，
                        // 所以增加健康穴數、穴數調整原因編號、穴數調整原因名稱，預設空值。
                        data.moldList[i].cavity_health_qty = '';
                        data.moldList[i].cavity_reason_no = '';
                        data.moldList[i].cavity_reason_name = '';
                    };
                    openDialog(data);
                });
        
            };
        }]);
});
